# -*- coding: utf-8 -*-

# from PyQt4                              import QtCore
# from utils.utils                        import getExeFromPath

from UI.UI_launch_config_dial           import Ui_manage_launch_config_dial
from new_config_dial                    import NewConfigDial
from PyQt4                              import QtGui
from constants.constants                import TABLE_LAUNCH_CONFIGURATIONS
from constants.constants                import TABLE_NAME_CONFIGURATIONS
from constants.constants                import TABLE_ACTION_LAUNCH_REL
from utils.utils                        import getIconPathFromExe
from utils.utils                        import setTheme
import os


class LaunchConfigDial(QtGui.QDialog,Ui_manage_launch_config_dial,QtGui.QWidget):
    def __init__(self, parent=None, dbInst=None, menuObj=None, exeList=[]):
        super(LaunchConfigDial,self).__init__(parent=parent)
        self.dbInst = dbInst
        self.menuObj = menuObj
        self.setupUi(self)
        self.initFields()
        self.setEvents()
        self.exeList = exeList
        setTheme(self)
            
    def initFields(self,):
        confObjects = self.dbInst.getRowsTable(TABLE_NAME_CONFIGURATIONS, fields=['config_value'], filtersList=[('config_name', '=', 'LAUNCH_CONFIG_HEADERS_ORDER')])
        self.config_headers_order = eval(confObjects[0].config_value)
        self.localLaunchObjs = []
        self.allLaunchObjs = []
        self.tableWidget_local.setColumnCount(len(self.config_headers_order))
        self.tableWidget_local.setHorizontalHeaderLabels(self.config_headers_order)
        self.tableWidget_local.horizontalHeader().setStretchLastSection(True)
        self.tableWidget_local.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        avaibleRelations    = self.dbInst.getRowsTable(TABLE_ACTION_LAUNCH_REL,[],[('act_id','=',self.menuObj.id)])
        self.setLocalLaunch(avaibleRelations)

    def setEvents(self):
        self.pushButton_create.clicked.connect(self.buttonCreate)
        self.pushButton_delete.clicked.connect(self.buttonDelete)
        self.buttonBox.accepted.connect(self.acceptAskForm)
        self.buttonBox.rejected.connect(self.rejectAskForm)
        self.horizontalSlider.sliderMoved.connect(self.changeTransparency)
        self.lineEdit_search_local.textChanged.connect(self.changedSearchLocal)
    
    def buttonCreate(self):
        dial = NewConfigDial(parent=self)
        if dial.exec_() == QtGui.QDialog.Accepted:
            customFlag = dial.radioButton_custom.isChecked()
            pathsToAdd = []
            if customFlag:
                pathsToAdd.append(dial.lineEdit_out_path.text())
            else:
                indexes = dial.listWidget.selectedIndexes()
                for index in indexes:
                    pathsToAdd.append(index.data().toString())
        
            for exePath in pathsToAdd:
                newRowCount = self.tableWidget_local.rowCount() +1
                self.tableWidget_local.setRowCount(newRowCount)
                iconPath = getIconPathFromExe(exePath)
                iconObj = QtGui.QIcon(iconPath)
                colIndexName = self.config_headers_order.index('name')
                colIndexExe = self.config_headers_order.index('exe_path')
                fileBaseName = os.path.basename(unicode(exePath))
                fileName = fileBaseName.split('.')[0]
                self.tableWidget_local.setItem(newRowCount-1 , colIndexName, QtGui.QTableWidgetItem(iconObj, fileName)) # name
                self.tableWidget_local.setItem(newRowCount-1 , colIndexExe, QtGui.QTableWidgetItem(exePath))      # exe_path
    
    def buttonDelete(self):
        self.removeRowsFromTable(self.tableWidget_local, self.getSelectedIndexesLocalConfig())

    def removeRowsFromTable(self, table, rowIndexesSelected):
        rowIndexesSelected.sort()
        rowIndexesSelected.reverse()
        for selectedIndex in rowIndexesSelected:
            table.removeRow(selectedIndex)

    def changedSearchLocal(self, newVal):
        self.setCommonFilter(newVal, self.localLaunchObjs, self.tableWidget_local)
        
    def setCommonFilter(self, newVal, objList, tableWidget):
        revList = []
        for obj in objList:
            if str(newVal).upper() in str(obj.name).upper():
                revList.append(obj)
        tableWidget.clear()
        tableWidget.setRowCount(0)
        self.setRowsToTableWidget(tableWidget, revList)
        
    def filterAllAvaibleConfig(self, alreadyUsedObjs, allAvaibleObjs):
        outObjs = []
        for allAvaible in allAvaibleObjs:
            found = False
            for usedObj in alreadyUsedObjs:
                if allAvaible.id == usedObj.id:
                    found = True
                    break
            if not found:
                outObjs.append(allAvaible)
        return outObjs
    
    def setRowsToTableWidget(self, tableWidget, rowsTable):
        outExeList = []
        for rowObj in rowsTable:
            currentRowCount = tableWidget.rowCount()
            tableWidget.setRowCount(currentRowCount+1)
            iconPath = getIconPathFromExe(rowObj.exe_path)
            outExeList.append(rowObj)
            iconObj = QtGui.QIcon(iconPath)
            tableWidget.setItem(currentRowCount, self.config_headers_order.index('exe_path'), QtGui.QTableWidgetItem(rowObj.exe_path))
            tableWidget.setItem(currentRowCount, self.config_headers_order.index('name'), QtGui.QTableWidgetItem(iconObj, rowObj.name))
            tableWidget.setItem(currentRowCount, self.config_headers_order.index('description'), QtGui.QTableWidgetItem(rowObj.description))
        return outExeList
            
    def setLocalLaunch(self, avaibleRelations):
        launchIds = []
        for relationObj in avaibleRelations:
            launchIds.append(relationObj.launch_id)
        rowsTable = self.dbInst.getRowsTable(TABLE_LAUNCH_CONFIGURATIONS,[],[('id','in',launchIds)])
        self.localLaunchObjs = self.setRowsToTableWidget(self.tableWidget_local, rowsTable)
        return rowsTable

    def getCommonSelectedRows(self, tableWidget):
        if tableWidget:
            indexes = tableWidget.selectedIndexes()
            rowIndexesSelected = []
            for index in indexes:
                if index.row() not in rowIndexesSelected:
                    rowIndexesSelected.append(index.row())
            return rowIndexesSelected

    def getSelectedIndexesLocalConfig(self):
        return self.getCommonSelectedRows(self.tableWidget_local)

    def changeTransparency(self, value=0):
        outVal = 100 - value
        self.setWindowOpacity(outVal/100.)
        
    def collectInfos(self):
        self.outObjects = []
        for rowCount in range(self.tableWidget_local.rowCount()):
            singleObj = ActionObj(self.config_headers_order)
            for colName in self.config_headers_order:
                conIndex = self.config_headers_order.index(colName)
                item = self.tableWidget_local.item(rowCount, conIndex)
                if item:
                    singleObj.__dict__[colName] = item.text()
                else:
                    singleObj.__dict__[colName] = ''
            self.outObjects.append(singleObj)
        
    def acceptAskForm(self):
        self.collectInfos()
        self.accept()
        
    def rejectAskForm(self):
        self.reject()

class ActionObj(object):
    def __init__(self, headers):
        for header in headers:
            self.__dict__[header] = ''
        return super(ActionObj, self).__init__()
